﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using Autofac.Core;

namespace Dexter.Dependency.Autofac.Extensions {
	internal static class ContainerExtensions {
		//more info here http://stackoverflow.com/questions/4959148/is-it-possible-in-autofac-to-resolve-all-services-for-a-type-even-if-they-were-r

		public static IEnumerable <T> ResolveAll <T> ( this IContainer container ) {
			return container.Resolve<IEnumerable<T>> ( );
		}

		public static IEnumerable<object> ResolveAll ( this IContainer container , Type type) {
			var allKeys = new List <object> ( );

			foreach ( var componentRegistration in container.ComponentRegistry.Registrations ) {
				var typedServices = componentRegistration.Services.Where ( x => x is KeyedService ).Cast <KeyedService> ( );
				allKeys.AddRange ( typedServices.Where ( y => y.ServiceType == type ).Select ( x => x.ServiceKey ) );
			}

			return allKeys;
		}
	}
}